package ying.request;/**
 * ClassName: ReqUploadDemo01
 * Package: ying.request
 * Description:
 *
 * @Author 刘英杰
 * @Create 2024/10/4 15:51
 * @Version 1.0
 */

import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@WebServlet("/req/upload01")
@MultipartConfig //上传文件
public class ReqUploadDemo01 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //如果上传的中文文件名乱码请使用以下语句
        //request.setCharacterEncoding("UTF-8");

        //1.通过request对象来获取Part接口实现类对象(改对象中封装了上传文件的相关信息)
        Part uploadFile = request.getPart("uploadFile");
        //2.通过Part接口的实现类对象获取上传文件的相关信息
//        System.out.println(uploadFile.getSubmittedFileName());
        String fileName = uploadFile.getSubmittedFileName();
        //3.保证存储文件名唯一,可以让用户重复上传文件
        String extension = fileName.substring(fileName.lastIndexOf(".")); //文件后缀
        String newFileName = UUID.randomUUID() + extension;
        //4.规定将文件上传到D:/uploadFile文件夹下
        File dir = new File("E:/uploadFile");
        if (!dir.exists()) {
            dir.mkdirs();
        }
        //4.将上传的文件写入到指定的路径
        uploadFile.write(dir + "/" + newFileName);
        //回应中文信息时,避免乱码
        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().write(fileName + " 上传成功");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
